package nina.yiyou.attendance.s30pattern.output.excel

import luj.ava.file.path.PathX
import org.apache.poi.ss.usermodel.CellStyle
import org.apache.poi.ss.usermodel.Sheet
import org.apache.poi.xssf.usermodel.XSSFWorkbook

import java.nio.file.Path
import java.time.LocalDateTime

class OutXlsxWriter {

  OutXlsxWriter(Path xlsxPath, List<String> header, List<List> body) {
    _xlsxPath = xlsxPath
    _header = header
    _body = body
  }

  void write() {
    println(_xlsxPath)
    String name = PathX.of(_xlsxPath).fileNameWithoutExtenstion

    def workbook = new XSSFWorkbook()
    def sheet = workbook.createSheet(name)
    writeHeader(sheet)

    CellStyle dateStyle = workbook.createCellStyle()
//    println(workbook.getCreationHelper().createDataFormat().getFormat((short)14))
    dateStyle.setDataFormat(14)

    _body.eachWithIndex { List row, int i ->
      writeRow(sheet, i + 1, row, dateStyle)
    }

    def out = new FileOutputStream(_xlsxPath.toFile())
    workbook.write(out)
    out.close()
  }

  private void writeHeader(Sheet sheet) {
    def row = sheet.createRow(0)

    _header.eachWithIndex { String v, int i ->
      def cell = row.createCell(i)
      cell.setCellValue(v)
    }

    sheet.createFreezePane(0, 1)
  }

  private void writeRow(Sheet sheet, int index, List row, CellStyle dateStyle) {
    def rowObj = sheet.createRow(index)

    row.eachWithIndex { Object val, int i ->
      def cell = rowObj.createCell(i)

      if (val instanceof LocalDateTime) {
        cell.setCellValue(val)
        cell.setCellStyle(dateStyle)
        return
      }

      cell.setCellValue(val)
    }
  }

  private final Path _xlsxPath

  private final List<String> _header
  private final List<List> _body
}
